import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import os
import glob
from pathlib import Path

class Spe2TifGenerator:
    def __init__(self, root):
        self.root = root
        self.root.title("SPE to TIF 宏代码生成器")
        self.root.geometry("800x600")
        
        # 输入路径变量
        self.input_path = tk.StringVar()
        self.output_path = tk.StringVar()
        
        self.create_widgets()
    
    def create_widgets(self):
        # 主框架
        main_frame = tk.Frame(self.root, padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = tk.Label(main_frame, text="SPE to TIF 宏代码生成器", 
                              font=("Arial", 16, "bold"))
        title_label.pack(pady=(0, 20))
        
        # 输入路径选择
        input_frame = tk.Frame(main_frame)
        input_frame.pack(fill=tk.X, pady=10)
        
        tk.Label(input_frame, text="输入路径 (包含.spe文件的文件夹):", 
                font=("Arial", 10)).pack(anchor=tk.W)
        
        input_path_frame = tk.Frame(input_frame)
        input_path_frame.pack(fill=tk.X, pady=5)
        
        tk.Entry(input_path_frame, textvariable=self.input_path, 
                font=("Arial", 10), width=50).pack(side=tk.LEFT, fill=tk.X, expand=True)
        tk.Button(input_path_frame, text="浏览", command=self.browse_input_path,
                 font=("Arial", 10)).pack(side=tk.RIGHT, padx=(10, 0))
        
        # 输出路径选择
        output_frame = tk.Frame(main_frame)
        output_frame.pack(fill=tk.X, pady=10)
        
        tk.Label(output_frame, text="输出路径 (TIF文件保存位置):", 
                font=("Arial", 10)).pack(anchor=tk.W)
        
        output_path_frame = tk.Frame(output_frame)
        output_path_frame.pack(fill=tk.X, pady=5)
        
        tk.Entry(output_path_frame, textvariable=self.output_path, 
                font=("Arial", 10), width=50).pack(side=tk.LEFT, fill=tk.X, expand=True)
        tk.Button(output_path_frame, text="浏览", command=self.browse_output_path,
                 font=("Arial", 10)).pack(side=tk.RIGHT, padx=(10, 0))
        
        # 生成按钮
        generate_frame = tk.Frame(main_frame)
        generate_frame.pack(pady=20)
        
        tk.Button(generate_frame, text="生成宏代码", command=self.generate_macro,
                 font=("Arial", 12, "bold"), bg="#4CAF50", fg="white",
                 padx=20, pady=10).pack()
        
        # 结果显示区域
        result_frame = tk.Frame(main_frame)
        result_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        tk.Label(result_frame, text="生成的宏代码:", 
                font=("Arial", 10, "bold")).pack(anchor=tk.W)
        
        self.result_text = scrolledtext.ScrolledText(result_frame, 
                                                   font=("Consolas", 10),
                                                   height=15)
        self.result_text.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 保存按钮
        save_frame = tk.Frame(main_frame)
        save_frame.pack(pady=10)
        
        tk.Button(save_frame, text="保存到文件", command=self.save_to_file,
                 font=("Arial", 10), bg="#2196F3", fg="white",
                 padx=15, pady=5).pack()
    
    def browse_input_path(self):
        path = filedialog.askdirectory(title="选择包含.spe文件的文件夹")
        if path:
            self.input_path.set(path)
    
    def browse_output_path(self):
        path = filedialog.askdirectory(title="选择TIF文件输出文件夹")
        if path:
            self.output_path.set(path)
    
    def generate_macro(self):
        input_path = self.input_path.get().strip()
        output_path = self.output_path.get().strip()
        
        if not input_path or not output_path:
            messagebox.showerror("错误", "请选择输入路径和输出路径")
            return
        
        if not os.path.exists(input_path):
            messagebox.showerror("错误", "输入路径不存在")
            return
        
        if not os.path.exists(output_path):
            try:
                os.makedirs(output_path)
            except Exception as e:
                messagebox.showerror("错误", f"无法创建输出路径: {str(e)}")
                return
        
        # 查找所有.spe文件
        spe_files = glob.glob(os.path.join(input_path, "*.spe"))
        
        if not spe_files:
            messagebox.showwarning("警告", "在指定路径中未找到.spe文件")
            return
        
        # 生成宏代码
        macro_code = []
        for spe_file in spe_files:
            filename = os.path.basename(spe_file)
            name_without_ext = os.path.splitext(filename)[0]
            
            # 使用绝对路径，避免跨驱动器问题，并转换为正斜杠
            abs_input_path = os.path.abspath(spe_file).replace('\\', '/')
            abs_output_path = os.path.abspath(os.path.join(output_path, f"{name_without_ext}.tif")).replace('\\', '/')
            
            macro_code.append(f'open("{abs_input_path}");')
            macro_code.append(f'saveAs("Tiff", "{abs_output_path}");')
            macro_code.append('close();')
            macro_code.append("")  # 空行分隔
        
        # 显示结果
        result = "\n".join(macro_code)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(1.0, result)
        
        messagebox.showinfo("成功", f"已找到 {len(spe_files)} 个.spe文件，宏代码已生成")
    
    def save_to_file(self):
        content = self.result_text.get(1.0, tk.END).strip()
        if not content:
            messagebox.showwarning("警告", "没有内容可保存")
            return
        
        file_path = filedialog.asksaveasfilename(
            title="保存宏代码文件",
            defaultextension=".ijm",
            filetypes=[("ImageJ Macro", "*.ijm"), ("Text files", "*.txt"), ("All files", "*.*")]
        )
        
        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                messagebox.showinfo("成功", f"宏代码已保存到: {file_path}")
            except Exception as e:
                messagebox.showerror("错误", f"保存文件失败: {str(e)}")

def main():
    root = tk.Tk()
    app = Spe2TifGenerator(root)
    root.mainloop()

if __name__ == "__main__":
    main() 